import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Progress, Table, Tag, Spin } from 'antd';
import { UserOutlined, TeamOutlined, CrownOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';

import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import type { User } from '@/services/generated';

interface UserStats {
  total: number;
  active: number;
  inactive: number;
  staff: number;
  superuser: number;
  recentUsers: User[];
}

const UserDashboard: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<UserStats>({
    total: 0,
    active: 0,
    inactive: 0,
    staff: 0,
    superuser: 0,
    recentUsers: [],
  });

  // 获取用户统计数据
  const fetchUserStats = async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      
      // 获取所有用户数据进行统计
      const response = await apiClients.users.usersList({
        page: 1,
        pageSize: 1000,
      });
      
      const users = response?.data?.items || [];
      
      const statsData: UserStats = {
        total: users.length,
        active: users.filter(u => u.status === 'active').length,
        inactive: users.filter(u => u.status !== 'active').length,
        staff: users.filter(u => u.is_staff).length,
        superuser: users.filter(u => u.is_superuser).length,
        recentUsers: users
          .sort((a, b) => new Date(b.created_at || '').getTime() - new Date(a.created_at || '').getTime())
          .slice(0, 10),
      };
      
      setStats(statsData);
    } catch (error: any) {
      console.error('获取用户统计失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserStats();
  }, []);

  const recentUsersColumns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          active: <Tag color="green">激活</Tag>,
          inactive: <Tag color="default">未激活</Tag>,
          suspended: <Tag color="red">暂停</Tag>,
        };
        return statusMap[status as keyof typeof statusMap] || <Tag>{status}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => date ? new Date(date).toLocaleDateString() : '-',
    },
  ];

  return (
    <PageContainer title="用户统计">
      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          {/* 统计卡片 */}
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="总用户数"
                value={stats.total}
                prefix={<TeamOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="激活用户"
                value={stats.active}
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
              <Progress 
                percent={stats.total > 0 ? Math.round((stats.active / stats.total) * 100) : 0} 
                size="small" 
                showInfo={false}
                strokeColor="#52c41a"
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="管理员"
                value={stats.staff}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
              <Progress 
                percent={stats.total > 0 ? Math.round((stats.staff / stats.total) * 100) : 0} 
                size="small" 
                showInfo={false}
                strokeColor="#fa8c16"
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="超级管理员"
                value={stats.superuser}
                prefix={<CrownOutlined />}
                valueStyle={{ color: '#f5222d' }}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
          {/* 最近注册用户 */}
          <Col xs={24} lg={16}>
            <Card title="最近注册用户" extra={<a href="/user/list">查看全部</a>}>
              <Table
                columns={recentUsersColumns}
                dataSource={stats.recentUsers}
                rowKey="id"
                pagination={false}
                size="small"
              />
            </Card>
          </Col>
          
          {/* 用户状态分布 */}
          <Col xs={24} lg={8}>
            <Card title="用户状态分布">
              <div style={{ padding: '20px 0' }}>
                <div style={{ marginBottom: 16 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                    <span>激活用户</span>
                    <span>{stats.active}</span>
                  </div>
                  <Progress 
                    percent={stats.total > 0 ? Math.round((stats.active / stats.total) * 100) : 0}
                    strokeColor="#52c41a"
                  />
                </div>
                
                <div style={{ marginBottom: 16 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                    <span>未激活用户</span>
                    <span>{stats.inactive}</span>
                  </div>
                  <Progress 
                    percent={stats.total > 0 ? Math.round((stats.inactive / stats.total) * 100) : 0}
                    strokeColor="#faad14"
                  />
                </div>
                
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                    <span>管理员用户</span>
                    <span>{stats.staff}</span>
                  </div>
                  <Progress 
                    percent={stats.total > 0 ? Math.round((stats.staff / stats.total) * 100) : 0}
                    strokeColor="#1890ff"
                  />
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </Spin>
    </PageContainer>
  );
};

export default UserDashboard;
